package com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;

/**
 * Created by Administrator on 2016/3/17.
 */
public class FileUtil {


    /**
     * 读取文本文件
     *
     * @param filePath 文件路径，必须包含文件名
     * @return
     */
    public static String readTextFile(String filePath) {
        InputStream fis = null;
        try {
            fis = new FileInputStream(filePath);
            byte[] buff = new byte[1024];
            int hasRead;
            StringBuilder sb = new StringBuilder();
            while ((hasRead = fis.read(buff)) > 0) {
                sb.append(new String(buff, 0, hasRead));
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 写文本文件
     *
     * @param filePath 文件路径，必须包含文件名
     * @param content  文件内容
     * @param isAppend 是否追加
     */
    public static void writeTextFile(String filePath, String content, boolean isAppend) {
        PrintStream ps = null;
        FileOutputStream fos = null;
        try {
            File file = new File(filePath);
            fos = new FileOutputStream(file, isAppend);
            ps = new PrintStream(fos);
            ps.println(content);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                ps.close();
            }
        }
    }

    /**
     * 写入二进制文件
     * @param contentBytes 字节数组
     * @param filePath 文件路径
     * @return 已写入的文件路径
     */
    public static String writeBinaryFile(byte[] contentBytes, String filePath) {
        FileOutputStream fileOutputStream = null;
        try {
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            }
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(contentBytes);
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
